package com.example.code.controller;

import com.example.code.service.CodeService;
import com.example.common.Code;
import com.example.common.ResultMessage;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author kangshuai
 */
@RestController
@RequestMapping("code")
public class CodeController {

    @Resource
    private CodeService codeService;

    /**
     * 创建验证码，保存到数据库中， 同时调用邮件服务发送邮件
     *
     * @param code
     * @return
     * @throws Exception
     */
    @PostMapping(value = "create", produces = {"application/json;charset=UTF-8"})
    public ResultMessage<Boolean> createCode(@RequestBody Code code) throws Exception {
        Boolean bool = codeService.createCode(code.getEmail());
        if (bool) {
            return ResultMessage.success(true);
        }
        return ResultMessage.error("验证码生成失败", false);
    }

    /**
     * 验证验证码
     *
     * @param code
     * @param code
     * @return
     * @throws Exception
     */
    @PostMapping(value = "verify", produces = {"application/json;charset=UTF-8"})
    public ResultMessage<Boolean> verify(@RequestBody Code code) throws Exception {
        try {
            ResultMessage<Boolean> resultMessage = codeService.verifyCode(code.getEmail(), code.getCode());
            return resultMessage;
        } catch (Exception e) {
            return ResultMessage.error("验证码验证错误", false);
        }
    }
}
